/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.middleware.quartz.job.jgupload;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ReportPlatformEnum;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.wlhy.company.entity.HyCompanyConfig;
import org.jeecg.modules.wlhy.company.service.IHyCompanyConfigService;
import org.jeecg.modules.wlhy.report.IReportService;
import org.jeecg.modules.wlhy.report.ReportServiceFactory;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * 上报脚本
 *
 * @author duanlikao
 * @created 2021/5/13
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
public class UploadJobService implements Job {

    public SimpleDateFormat now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private IHyCompanyConfigService companyConfigService;

    @Autowired
    private IHyShippingNoteService shippingNoteService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        List<HyCompanyConfig> companyConfigs = companyConfigService.list(new QueryWrapper<HyCompanyConfig>()
                .gt("report_platform_type", ReportPlatformEnum.REPORT_PLATFORM_NONE.getCode())
                .eq("auto_report",1)
        );
        if(CollectionUtils.isEmpty(companyConfigs)) {
            log.info("定时上报任务, 没有分公司配置自动上报" );
            return;
        }

        Long start = System.currentTimeMillis();
        log.info("定时上报任务,执行运单上报数据开始" + now.format(new Date()));

        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, -60);// 把日期往后增加一天.整数往后推,负数往前移动
        Date lasDate = calendar.getTime(); // 这个时间就是日期往后推一天的结果
        String startDateString =  DateUtils.date2Str(lasDate, DateUtils.date_sdf.get());
        String endDateString =  DateUtils.getDateStr();

        for (HyCompanyConfig companyConfig : companyConfigs) {
            //天津监管的跳过 天津监管上报特殊单独上报
            if (companyConfig.getReportPlatformType().equals(ReportPlatformEnum.REPORT_PLATFORM_TJ.getCode())){
                continue;
            }

            //淮北监管上报一些图片比较特殊，单独实现
            if (companyConfig.getReportPlatformType().equals(ReportPlatformEnum.REPORT_PLATFORM_HUAIBEI.getCode())) {
                continue;
            }

            try {
                //在getReport中做判断 如果report==null，抛异常
                IReportService  reportService = ReportServiceFactory.getReport(companyConfig.getReportPlatformType());
                //检查相关的上报是否开启，参数是否配置等操作
                reportService.checkReport();

                QueryWrapper<HyShippingNote> queryWrapper = new QueryWrapper();
                queryWrapper.eq("shipping_pay_status","6");
                queryWrapper.eq("company_id",companyConfig.getCompanyId());
                queryWrapper.ne("upload_status","1");
                //queryWrapper.eq("order_mode","1");//管理费模式
                queryWrapper.between("pay_dt",startDateString+" 00:00:00", endDateString );
                queryWrapper.orderByAsc("pay_dt");

                List<HyShippingNote> shippingNotes = shippingNoteService.list(queryWrapper);
                log.info("定时上报任务运单及资金流水数据, {} {}", JSONUtil.toJsonStr(companyConfig), shippingNotes.size());
                if (CollectionUtils.isEmpty(shippingNotes)) {
                    continue;
                }
                for (HyShippingNote hyShippingNote : shippingNotes) {
                    Result r = reportService.reportShippingNote(hyShippingNote);
                    if (!r.getCode().equals(CommonConstant.SC_OK_200)) {
                        log.warn("定时上报运单失败,{} {}", hyShippingNote.getShippingNoteNumber(), JSONUtil.toJsonStr(r));
                        continue;
                    }

                    Result r2 = reportService.reportCapitalFlow(hyShippingNote);
                    if (!r2.getCode().equals(CommonConstant.SC_OK_200)) {
                        log.warn("定时上报资金流水失败,{} {}", hyShippingNote.getShippingNoteNumber(), JSONUtil.toJsonStr(r2));
                        continue;
                    }

                    log.info("定时上报运单及资金流水成功, {} {}", companyConfig.getCompanyId(), hyShippingNote.getShippingNoteNumber());
                }

            } catch (Exception e) {
                log.info("定时上报任务异常 : {}" ,e.getMessage());
                continue ;
            }

        }
        log.info("定时上报任务，执行运单上报数据结束,耗时:"+(System.currentTimeMillis()-start)+"毫秒----");

        return;
    }




}
